import json

from apps.system.formRecord.baseViews import *
from apps.system.form.dao import FormDao


class FormRecordViewSet(BaseFormRecordViewSet):

    def get_queryset(self):
        params = getRequestParams(self.request)
        _list = FormRecordDao().findAll().select_related('form')
        return _list

    @action(methods=['post'], detail=False)
    def submitForm(self, request):
        params = getRequestParams(self.request)
        formKey = params.get('formKey')
        if isEmptyStr(formKey):
            return Response(response_message('formKey参数必填'))
        content = params.get('content')
        if not content:
            return Response(response_message('content参数必填'))

        contentStr = json.dumps(content, indent=4, ensure_ascii=False)

        forms = FormDao().findAll().filter(key=formKey)
        form = None
        if forms.exists():
            form = forms.first()
        data = {
            'form': form.id,
            'content': contentStr
        }
        data['requestUserId'] = request.user.id
        FormRecordDao().create(data)
        return Response(response_success('提交成功'))